<script setup lang="ts">
	import SectionTitle from '@/wxcomponents/section-title'
	import productItem from '@/wxcomponents/product-item'
	import ListItem from '@/wxcomponents/list-item'
	import ProductsSwiper2 from '@/wxcomponents/products-swiper-2'
	import PrizeDialogContent from '@/wxcomponents/prize-dialog-content'
	import MainWrapper from '@/wxcomponents/main-wrapper'
	import RecordContent from './shared/record-content'
	import GameRecharge from './shared/game-recharge'
	import PrizeGameTab from './shared/prize-game-tab/index.vue'
	import Pay from '@/wxcomponents/pay'
	import { loadYiFanShangDetail, listYiFanShangRecords, loadYiFanShangRemainCount } from "@/api/yifanshang";
	import { ref, computed } from 'vue'
	import { onLoad, onReachBottom, onShow,onPullDownRefresh } from "@dcloudio/uni-app";

	const tabs = ref(['赏品一览', '中奖记录', '购买说明'])
	const tab = ref('赏品一览')
	const isCouponModalVisible = ref(false)
	let gameId = ref(0)
	const detail = ref({})
	const dialogItem = ref({})
	let showBanners = []
	const rechargePrices = ref([])
	const remainCount = ref(0)
	const recordList = ref([])
	let payBoxShow = false

	// 服务器端统计的总数据量
	const recordListTotal = ref(null)

	// 中奖记录数据分页
	const recordListPage = ref(1)

	function goBack() {
		uni.switchTab({
			url: '/pages/index/index'
		})
	}
	// onShareAppMessage((res) => {
	// 	if (res.from === 'button') {
	// 		// 来自按钮的分享
	// 		// 返回分享的内容
	// 		return {
	// 			title: detail.value.name,
	// 			imageUrl: detail.value.main_photo// 分享卡片的图片，可选
	// 		}
	// 	}
	// })
	// function sharegame() {
	// 	wx.showShareMenu({
	// 		withShareTicket: true,
	// 		menus: ['shareAppMessage', 'shareTimeline']
	// 	});
	// }
	function showDialogImage(item) {
		dialogItem.value = {
			image: item.image,
			name: item.name,
			price: ((item.show_price) / 100).toFixed(2)
		}
		isCouponModalVisible.value = true
	}

	function closeCouponModal() {
		isCouponModalVisible.value = false;
	}
	async function loadYiFanShang() {
		const params = {
			game_id: gameId.value,
			game_type: '一番赏',
			index: 1
		}
		const res = await loadYiFanShangDetail(params)
		const data = res.data || {}

		let products = data.products || []
		const special_products = data.special_products || []

		let allProducts = []
		// 商品价格从单位分转为元
		for (let i = 0; i < special_products.length; i++) {
			special_products[i].price = (special_products[i].price / 100).toFixed(2)
			special_products[i].showStock = "数量:" + special_products[i].stock + "/" + special_products[i].count

			allProducts.push(special_products[i])
		}

		for (let i = 0; i < products.length; i++) {
			products[i].price = (products[i].price / 100).toFixed(2)
			products[i].showStock = "数量:" + products[i].stock + "/" + products[i].count
			allProducts.push(products[i])
		}
		data['products'] = allProducts

		showBanners = []
		for (let i = 0; i < data.banners.length; i++) {
			showBanners.push({
				'main_photo': data.banners[i]
			})
		}

		await loadYiFanShangCount()
		const buyCounts = [1, 5, 10]

		const newPrices = []
		for (let i = 0; i < buyCounts.length; i++) {
			const buyPrice = data['price'] * buyCounts[i]
			newPrices.push({
				'price': data['price'],
				'show_price': (buyPrice / 100).toFixed(2),
				'class': 'recharge-' + buyCounts[i],
				'count': buyCounts[i]
			})
		}
		newPrices.push({
			'price': data['price'],
			'show_price': 'all',
			'class': 'recharge-0',
			'count': remainCount.value
		})

		rechargePrices.value = newPrices


		detail.value = data

		const stockproduct = [
			{
				name: '剩余数量',
				stock: data.stock || 0,
				count: data.prize_count || 0
			}
		]
		for (let i = 0; i < data['products'].length; i++) {
			stockproduct.push({
				name: data['products'][i]['name'],
				stock: data['products'][i]['stock'],
				count: data['products'][i]['count']
			})
		}

		detail.value.stockproduct = stockproduct
	}

	async function loadYiFanShangCount() {
		const params = {
			game_id: gameId.value,
			game_type: '一番赏',
			game_index: 1,
		}
		const res = await loadYiFanShangRemainCount(params)
		const data = res.data || {}
		const count = data.count || 0
		remainCount.value = count
	}

	async function listRecords({ refresh = true }) {
		if (tab.value !== '中奖记录') {
			return
		}

		if (!refresh && recordListTotal.value === recordList.value.length) {
			// 已获取了全部数据量，不再发送加载更多的请求
			return
		}

		const params = {
			page: refresh ? 1 : recordListPage.value + 1,
			size: 15,
			game_id: gameId.value,
			type: '一番赏',
			index: 1
		}

		const res = await listYiFanShangRecords(params)
		const data = res.data || {}
		const items = data['items'] || []
		recordListTotal.value = data.total
		recordList.value = refresh ? items : recordList.value.concat(items)
		recordListPage.value = params.page
	}
	let safetop = ref(0)
	function getsafetop() {
		uni.getSystemInfo({
			success: function (res) {
				// res.safeAreaInsets 包含了 safeAreaInsets.top 和 safeAreaInsets.bottom
				safetop.value = res.safeAreaInsets.top;
			}
		});
	}
	onLoad(async (options) => {
		getsafetop()
		const id = options.id || 0
		if (!id) {
			uni.showToast({
				title: 'id参数错误',
				icon: 'none'
			})
			return
		}
		gameId.value = id

		await loadYiFanShang()
		uni.$mpShare = shareData.value // 修改uni.$mpShare的值

	});
	onPullDownRefresh(async () => {
		await loadYiFanShang()
		uni.stopPullDownRefresh()
	})
	onShow(() => {
		uni.$mpShare = shareData.value // 修改uni.$mpShare的值
	})
	const shareData = computed(() => { // 分享的数据
		return {
			title: detail.value.name,
			imageUrl: detail.value.main_photo
		}
	})
	onReachBottom(async () => {
		if (tab.value !== '中奖记录') {
			return
		}
		await listRecords({ refresh: false })
	})

	async function changeTab(tab) {
		switch (tab) {
			case '赏品一览':
				await loadYiFanShang()
				return

			case '中奖记录':
				await listRecords({ refresh: true });
				return
		}
	}

	async function onPaySuccess() {
		// 付款成功后刷新数据
		// 这里借用切换 Tab 的逻辑，即将付款成功后的操作等价于刷新当前 Tab 页
		await changeTab(tab.value)
	}
</script>

<template>
	<!--  -->
	<main-wrapper with-bottom bg="https://dongke-common.oss-cn-shenzhen.aliyuncs.com/garage-kit/changebox-bg.png">
		<view class="page-head" :style="{top:safetop+'px'}">
			<uni-icons type="arrow-left" color="white" size="30" @click="goBack"></uni-icons>
			<section-title title="一番赏" />
		</view>

		<van-dialog use-slot :show="isCouponModalVisible" :show-confirm-button="false" width="312">
			<prize-dialog-content :image="dialogItem.image" :name="dialogItem.name" :price="dialogItem.price"
				v-on:close="closeCouponModal" />
		</van-dialog>

		<products-swiper-2 :data="showBanners" :products="detail.stockproduct" />

		<prize-game-tab v-model:tab="tab" :tabs="tabs" @change="() => changeTab(tab)"
			style="display: block; margin-top: 20px; " />

		<view class="tab-content">
			<view v-if="tab === '赏品一览'" class="products-list">
				<product-item v-for="(item, index) in detail.products" :key="index" :title="item.name" :pic="item.image"
					:price="item.price" :type="item.type" :percent="item.percent" class="product-item"
					:soldout="item.stock === 0" :bottom-text="item.showStock" @click="showDialogImage(item)" />
			</view>

			<view v-if="tab === '中奖记录'" class="combat-records">
				<template v-for="(item, index) in recordList" :key="index">
					<list-item>
						<record-content :avatar-src="item.avatar" :name="item.nickname" :datetime="item.created_at"
							:prize-type="item.type" :prize-name="item.name" style="width: 100%" />
					</list-item>
				</template>

				<view v-if="recordListTotal === recordList.length"></view>
			</view>

			<view v-if="tab === '购买说明'">
				<view class="text-box">
					<image class="bg"
						src="https://dongke-common.oss-cn-shenzhen.aliyuncs.com/garage-kit/text-board-bg.png"
						mode="widthFix"></image>
					<view class="text">
						<text>购买说明</text>
					</view>
					<scroll-view scroll-y="true" style="height: 126px; margin-top: 16px">
						<view class="content">
							<text class="content-text">
								{{ detail.instruction }}
							</text>
						</view>
					</scroll-view>
				</view>
			</view>
		</view>

		<!--
      <view class="products-list">
        <template v-for="(e, index) in new Array(8)" :key="index">
          <product-item
            title="一番赏 龙珠 基纽雪未来的语言的华语"
            pic="https://dongke-common.oss-cn-shenzhen.aliyuncs.com/garage-kit/product-example.png"
            price="0/1"
            badge="普通款"
          />
        </template>
      </view>
    </view>
    -->

		<game-recharge class="bottom-panel" :title="detail.title" :gameId="detail.id" :gameIndex="1"
			:gameType="detail.type" :image="detail.main_photo" :price="detail.price" :prices="rechargePrices"
			:ifFull="0" @success="onPaySuccess" />
	</main-wrapper>
</template>

<style>
	/* page {
		background-color: #0A050B;
	} */
</style>

<style lang="scss">
	@import 'src/static/scss/maincommon';

	// .page-head {
	//   position: fixed;
	//   display: flex;
	//   top: 0;
	//   gap: 10px;
	//   width: 150px;
	//   line-height: 88px;
	//   z-index: 100;
	// }
	.page-head {
		position: fixed;
		display: flex;
		top: 0;
		gap: 10px;
		width: 150px;
		// line-height: 88px;
		align-items: center;
		z-index: 100;
	}

	.tab-content {
		margin-top: 1em;
	}

	.products-list {
		gap: 10px;
		display: grid;
		grid-template-columns: 1fr 1fr 1fr;
	}

	.product-item {
		display: flex;
		justify-content: space-around;
	}

	.with-bottom-panel {
		position: relative;
		padding-bottom: 200px;
	}

	.bottom-panel {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
	}

	.text-box {
		width: 100%;
		aspect-ratio: 702/384;
		display: flex;
		overflow-y: hidden;
		align-items: flex-start;
		justify-content: flex-start;
		flex-direction: column;
		box-sizing: border-box;
		padding: 22px 18px 0;
		color: white;
		position: relative;
	}

	.text-box .title {
		font-size: 14px;
		margin-bottom: 10px;
	}

	.text-box .content {
		font-size: 10px;
		line-height: 18px;
		overflow-y: scroll;
		padding-bottom: 20px;
	}

	.text-box .bg {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
	}
</style>